package org.tgit.gateway.config;

import java.sql.SQLException;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.tgit.gateway.common.ApiConstants;
import org.tgit.gateway.common.CommonUtil;
import org.tgit.gateway.common.GatewayException;
import org.tgit.gateway.common.TgitResponse;

import reactor.core.publisher.Mono;

@Aspect
@Component
public class AopConfig {
	private static final Logger LOGGER=LoggerFactory.getLogger(AopConfig.class);
	/**
	 * 
	* @Title: api   
	* @Description: 制定切入点
	* @author fanzaijun  
	* @date 2018年10月25日 下午3:01:54     
	* void  
	* @throws (没有异常抛出)
	 */
	@Pointcut("execution(public * org.tgit.gateway.controller.**.*(..))")
	public void api() {};
	
	/**
	 * 
	* @Title: invokeAction   
	* @Description: 环绕通知-控制方法的执行
	* @author fanzaijun  
	* @date 2018年10月25日 下午3:12:57   
	* @param pjp
	* @return
	* @throws Throwable  
	* Object  
	* @throws (没有异常抛出)
	 */
	@Around("api()")
	public Object invokeAction(ProceedingJoinPoint pjp) throws Throwable{
		//开始时间设定
		long beginTime=System.currentTimeMillis();
		//记录请求到响应时间-初始化
		long reqToResTime=0;
		//获取的类名称
		String className=pjp.getSignature().getDeclaringTypeName();
		//获取的方法名称
		String methodName=pjp.getSignature().getName();
		//参数获取
		Object[] args=pjp.getArgs();
		//打印请求入参：
		LOGGER.info(CommonUtil.getMsg(ApiConstants.REQ,className,methodName,args));
		//Controller方法执行
		try {
			Object rsp=pjp.proceed();
			//记录请求到响应时间
			reqToResTime=System.currentTimeMillis()-beginTime;
			LOGGER.info(CommonUtil.getMsg(ApiConstants.RSP, className, methodName, reqToResTime));
			//rsp:Mono
			return rsp;
		}catch (GatewayException e) {
			TgitResponse rsp = new TgitResponse();
            rsp.setAppCode(e.getCode());
            rsp.setMessage(e.getMsg());
            reqToResTime=System.currentTimeMillis()-beginTime;
            LOGGER.error(CommonUtil.getMsg(ApiConstants.RSP,className,methodName,rsp,reqToResTime),e);
            return Mono.just(rsp);
		}catch (SQLException e) {
			TgitResponse rsp = new TgitResponse();
            rsp.setAppCode(ApiConstants.DB_CONNECT_ERROR);
            rsp.setMessage(ApiConstants.getErrorMsg(ApiConstants.DB_CONNECT_ERROR));
            reqToResTime=System.currentTimeMillis()-beginTime;
            LOGGER.error(CommonUtil.getMsg(ApiConstants.RSP,className,methodName,rsp,reqToResTime),e);
            return Mono.just(rsp);
		}
	}

}
